<template>
  <el-dialog :visible="showRoleDialog" title="分配角色" @open="getUserDetailById(userId)" @close="clear">
    <el-row style="height:50px">
      <el-checkbox-group v-model="checkList">
        <el-checkbox v-for="obj in roleList" :key="obj.id" :label="obj.name" />
      </el-checkbox-group>
    </el-row>
    <el-row type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" @click="updaRole">提交</el-button>
        <el-button @click="clear">取消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getRoleList, getRoles } from '@/api/setting'
import { getUserDetailById } from '@/api/user'
import { updaRole } from '@/api/employees'
export default {
  props: {
    showRoleDialog: {
      type: Boolean,
      default: false
    },
    // 用户的id 用来查询当前用户的角色信息
    userId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      checkList: [], // 复选框的值
      roleList: [], // 获取所有角色列表
      dataRole: {}
    }
  },
  async created() {
    this.getRoleList()
  },
  methods: {
    async getRoleList() {
      const { rows } = await getRoleList()
      // console.log(rows)
      this.roleList = rows
      // console.log(this.roleList)
    },
    async getUserDetailById(id) {
      // console.log(id)
      const result = await getUserDetailById(id)
      // console.log(result.roleIds)
      const result1 = await getRoles()
      // console.log(result1)
      const list = []
      result1.forEach(obj => {
        return result.roleIds.forEach(item => {
          if (obj.id === item) {
            list.push(obj.name)
          }
        })
      })
      this.checkList = list
      // console.log(this.checkList)
    },
    async updaRole() {
      this.dataRole.id = this.userId
      const arr = []
      this.roleList.forEach(obj => {
        this.checkList.forEach(item => {
          if (item === obj.name) {
            arr.push(obj.id)
          }
        })
      })
      this.dataRole.roleIds = arr
      // console.log(this.dataRole)
      await updaRole(this.dataRole)
      this.$message.success('更改权限成功')
      this.$emit('update:showRoleDialog', false)
    },
    clear() {
      this.$emit('update:showRoleDialog', false)
    }
  }
}
</script>

<style>

</style>
